import store from '../store'
export default {
	getLocation(flag) {
		return new Promise((resolve, reject) => {

			let location = this.getLocationCache();
			if (location) {
				return resolve(location);
			}

			// #ifdef H5
			// if (uni.$jswx.isWechat()) {
			// 	uni.$jswx.getLocation().then((res) => {
			// 		resolve(res)
			// 	}).catch(() => {
			// 		uni.getLocation({
			// 			success: (res) => {
			// 				this.setLocation(res);
			// 				resolve(res)
			// 			},
			// 			fail: (err) => {
			// 				resolve()
			// 			}
			// 		})
			// 	})
			// } else {
			uni.getLocation({
				success: (res) => {
					this.setLocation(res);
					resolve(res)
				},
				fail: (res) => {
					resolve()
				},
				complete: (res) => {
					console.log(res)
				}
			})
			// }
			// #endif


			// #ifndef H5
			let that = this;
			uni.getLocation({
				success: (res) => {
					console.log(res)
					this.setLocation(res);
					resolve(res)
				},
				fail: (res) => {
					resolve()
				}
			})
			// #endif
		})
	},

	setLocation(location) {
		uni.setStorageSync("location_time", new Date().getTime())
		uni.setStorageSync("location", location);
	},

	getLocationCache() {

		let location_time = uni.getStorageSync("location_time");
		if (!location_time || (new Date().getTime() - parseInt(uni.getStorageSync("location_time")) > 3600000)) {
			return null;
		}
		return uni.getStorageSync("location");
	},

	chooseLocation() {
		return new Promise((resolve, reject) => {
			// #ifdef H5
			if (uni.$jswx.isWechat()) {
				uni.$jswx.getLocation((res, err) => {
					if (res) {
						console.log("chooseLocation1--", res)
						uni.chooseLocation({
							latitude: res.latitude,
							longitude: res.longitude,
							success: (res1) => {
								console.log("chooseLocation2--", res1)
								resolve(res1)
							},
							fail: (err) => {
								console.log("chooseLocation3--", err)
								reject(err);
							}
						})
					} else {
						uni.chooseLocation({
							success: (res1) => {
								resolve(res1)
							},
							fail: (err) => {
								reject(err);
							}
						})
					}

				})
			}
			// #endif
			uni.chooseLocation({
				success: (res1) => {
					resolve(res1)
				},
				fail: (err) => {
					reject(err);
				}
			})

			// #ifdef APP


			// #endif
		});


	},
}
